package com.cvte.boe.media.views.widget;

/**
 * Created by wuguitong on 2018/5/17.
 */

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class ReflectionImage extends ImageView {
    public ReflectionImage(Context context) {
        super(context);
    }

    public ReflectionImage(Context context, AttributeSet attrs) {
        super(context, attrs);
        measure(0, 0);
        Bitmap originalImage = ((BitmapDrawable) this.getDrawable()).getBitmap();
        super.setImageBitmap(getReflectionBitmap(originalImage));
    }

    public ReflectionImage(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        Bitmap originalImage = ((BitmapDrawable) this.getDrawable()).getBitmap();
        super.setImageBitmap(getReflectionBitmap(originalImage));
    }

    @Override
    public void setImageResource(int resId) {
        Bitmap originalImage = BitmapFactory.decodeResource(getResources(), resId);
        super.setImageBitmap(getReflectionBitmap(originalImage));
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(getReflectionBitmap(bm));
    }

    private Bitmap getReflectionBitmap(Bitmap originalImage) {
        final int reflectionGap = 0;
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);
        Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height * 2 / 3, width, height * 1 / 3, matrix, false);
        Bitmap bitmap4Reflection = Bitmap.createBitmap(width, (height + height * 1 / 3), Config.ARGB_8888);
        Canvas canvasRef = new Canvas(bitmap4Reflection);
        canvasRef.drawBitmap(originalImage, 0, 0, null);
        Paint deafaultPaint = new Paint();
        canvasRef.drawRect(0, height, width, height + reflectionGap, deafaultPaint);
        canvasRef.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
        Paint paint = new Paint();
        LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0, bitmap4Reflection.getHeight()
                + reflectionGap, 0xb0ffffff, 0x00ffffff, TileMode.CLAMP);
        paint.setShader(shader);
        paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
        canvasRef.drawRect(0, height, width, bitmap4Reflection.getHeight() + reflectionGap, paint);
        return bitmap4Reflection;
    }
}
